import random
import threading
import time
from datetime import datetime, timedelta
from typing import List, Dict
from .base import BaseDataFeed
from common.data_models import TickData, BarData, DataType

class MockDataFeed(BaseDataFeed):
    """模拟数据源 - 用于开发和测试"""
    
    def __init__(self, config: Dict):
        super().__init__(config)
        self._running = False
        self._thread = None
        self.base_prices = {
            'BTC/USDT': 50000.0,
            'ETH/USDT': 3000.0,
            'ADA/USDT': 0.5
        }
        
    def connect(self) -> bool:
        """启动模拟数据流"""
        if self.connected:
            self.logger.warning("已经连接")
            return True
            
        try:
            self._running = True
            self.connected = True
            
            # 启动数据生成线程
            self._thread = threading.Thread(target=self._data_generator)
            self._thread.daemon = True
            self._thread.start()
            
            self.logger.info("模拟数据源连接成功")
            return True
            
        except Exception as e:
            self.logger.error(f"模拟数据源连接失败: {e}")
            return False
            
    def disconnect(self):
        """断开连接"""
        self._running = False
        self.connected = False
        if self._thread:
            self._thread.join(timeout=5)
        self.logger.info("模拟数据源已断开")
        
    def subscribe(self, symbols: List[str], data_type: DataType = DataType.TICK):
        """订阅符号"""
        for symbol in symbols:
            self.subscribed_symbols.add(symbol)
            self.logger.info(f"订阅 {symbol} ({data_type.value})")
        
    def unsubscribe(self, symbols: List[str], data_type: DataType = DataType.TICK):
        """取消订阅"""
        for symbol in symbols:
            if symbol in self.subscribed_symbols:
                self.subscribed_symbols.remove(symbol)
                self.logger.info(f"取消订阅 {symbol} ({data_type.value})")
                
    def _data_generator(self):
        """模拟数据生成器"""
        self.logger.info("启动模拟数据生成器")
        
        while self._running and self.connected:
            if not self.subscribed_symbols:
                time.sleep(1)
                continue
                
            for symbol in list(self.subscribed_symbols):
                # 生成Tick数据
                tick = self._generate_tick_data(symbol)
                self.on_tick_data(tick)
                
            time.sleep(0.1)  # 10次/秒
            
    def _generate_tick_data(self, symbol: str) -> TickData:
        """生成模拟Tick数据"""
        base_price = self.base_prices.get(symbol, 100.0)
        
        # 模拟价格波动 (-0.1% 到 +0.1%)
        price_change = random.uniform(-0.001, 0.001)
        new_price = base_price * (1 + price_change)
        self.base_prices[symbol] = new_price
        
        # 生成买卖盘
        spread = new_price * 0.0002  # 0.02% 价差
        bid_price = new_price - spread / 2
        ask_price = new_price + spread / 2
        
        return TickData(
            symbol=symbol,
            price=new_price,
            volume=random.uniform(1, 100),
            timestamp=datetime.now(),
            bid_price=round(bid_price, 2),
            ask_price=round(ask_price, 2),
            bid_volume=random.uniform(10, 1000),
            ask_volume=random.uniform(10, 1000)
        )